package com.cdyx.yygh.cmn.service.impl;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdyx.model.cmn.Dict;
import com.cdyx.vo.cmn.DictEeVo;
import com.cdyx.vo.cmn.DictVo;
import com.cdyx.yygh.cmn.listener.Listener;
import com.cdyx.yygh.cmn.mapper.DictMapper;
import com.cdyx.yygh.cmn.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    DictMapper dictMapper;
//根据id查询子数据列表
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        for (Dict dict:dictList
             ) {
            Long dictId = dict.getId();
            boolean children = isChildren(dictId);
            if (children)
                dict.setHasChildren(true);
        }
        return dictList;
    }
    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void downloadExcel(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileCode = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition","attachment;filename="+fileCode+".xlsx");
            List<Dict> dicts = baseMapper.selectList(null);
            List<DictEeVo> list=new ArrayList<>();
            //将Dict 转换为DictEeVo
            for (Dict dic:dicts
                 ) {
                DictEeVo dictVo=new DictEeVo();
                BeanUtils.copyProperties(dic, dictVo);//类似把dic的每个属性赋值给dictVo对象的属性
                if (dictVo.getDictCode()!=null){
                    byte[] code = dictVo.getDictCode().getBytes();
                    String newcode = Base64.getEncoder().encodeToString(code);
                    System.out.println(newcode);
                    dictVo.setDictCode(newcode);
                }
                byte[] name = dictVo.getName().getBytes();
                String newname= Base64.getEncoder().encodeToString(name);
                System.out.println(newname);
                dictVo.setName(newname);
                if (dictVo.getValue()!=null) {
                    byte[] value = dictVo.getValue().getBytes();
                    String newvalue = Base64.getEncoder().encodeToString(value);
                    dictVo.setValue(newvalue);
                    System.out.println(newvalue);
                }
                byte[] id = dictVo.getId().toString().getBytes();
                byte[] pid = dictVo.getParentId().toString().getBytes();
                String newId = Base64.getEncoder().encodeToString(id);
                dictVo.setNewId(newId);
                String newPid = Base64.getEncoder().encodeToString(pid);
                dictVo.setNewParentId(newPid);
                list.add(dictVo);
            }
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("dict").doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new Listener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断id下面是否有子节点
    private boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
